﻿using ConAppCore.Test;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using UtilZ.Dotnet.Ex.Attributes;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.DataStatistic;
using UtilZ.Dotnet.Ex.DataStruct;
using UtilZ.Dotnet.Ex.Json;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.Ex.Model;
using UtilZ.Dotnet.Ex.ZLog;

namespace ConAppCore
{
    unsafe class Program
    {
        static void Main(string[] args)
        {
            //DemoeCode();
            //GenerateErrorCode();
            //TestCode();

            //int code1 = "一级保密资格单位应当对在岗涉密人员进行保密教育培训".GetHashCode();
            //int code2 = "一级保密资格单位应当对在岗涉密人员进行保密教育培训".GetHashCode();
            //int xx=code1 + code2;

            //byte leftValue = 40;
            //byte rightValue = 34;
            //var ret1 = leftValue.CompareTo(rightValue);//6
            //var ret2 = rightValue.CompareTo(leftValue);//-6

            //int leftValue2 = 40;
            //int rightValue2 = 34;
            //var ret3 = leftValue2.CompareTo(rightValue2);//1
            //var ret4 = rightValue2.CompareTo(leftValue2);//-1

            //var ret3 = ((byte)40).CompareTo((byte)34);

            //using var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            //var versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(currentProcess.MainModule.FileName);

            InitLog();

            //string filePath = @"D:\sigALL\20250311165302_IQ_AAAAAA7100ZD03_F_0118300000_B_0000200000_S_0000256000_456.wav";
            //WaveHelper.FillWavHead(filePath, 16, 256000, 2, -1);

            //TestLog();
            //TestConfig.Test();
            //TestPathEx.Test();
            //TestConvertEx.Test();
            //Json.JsonTest.Test(args);
            //TestJWT.Test();

            //TestHuffmanTree.Test();
            //TestTelnetServer.Test();
            //TestObjectBuilder.Test();
            //TestStreamEx.Test();
            //TestFtpServer.Test();
            //TestStringEx.Test();
            //TestTimingTask.Test();
            //TestTimeEX.Test();
            //TestMemoryCacheEx.Test();

            //TestAsynQueue.Test();
            //TestMathEx.Test();
            //TestTypeEx.Test();
            //TestParaManager.Test();
            //TestNetTcpListener.Test();
            //TestNetTcpClient.Test();
            //TestNetUdpClient.Test();
            //TestHttpServer.Test();

            //TestTransferData.Test();
            //TestMemoryMappedFile.Test();
            //TestParaRangeManager.Test();
            //TestAsynQueueZ.Test();            
            //TestThreadEx.Test();
            //TestSpinWaiter.Test();
            //TestEnumerableEx.Test();
            //TestSignalHelper.Test();
            //TestObjectEx.Test();
            //TestProcessMonitor.Test();
            //TestProcessEx.Test();
            //TestEnvironmentEx.Test();
            //TestMarshalEx.Test();
            //TestObjectPool.Test();
            //TestSpeedLimiter.Test();
            //TestUnmanagedMemoryPointer.Test();
            //TestValueDescriptionManager.Test();
            //TestArrayEx.Test();
            //TestFourierEx.Test();
            //TestDataMerger.Test();
            //TestDisposablerItem.Test();
            //TestUnsafeAccessor.Test();
            //TestValueTypeDataMerger.Test();
            //TestActivatorEx.Test();
            //TestBufferData.Test();
            //TestDataStatistic.Test();
            //TestExpireFileCleaner.Test();
            //TestMathNetEx.Test();
            //TestFileEx.Test();
            //TestFlexibleArray.Test();
            //TestAppConfigurationManager.Test();
            //TestSpinThread.Test();
            //TestPlugin.Test();
            //TestPerformanceStatistic.Test();
            //TestCommandParser.Test(args);

            //TestSpan.Test();
            //CodeConvert.Test();
            //TestNormalizer.Test();
            //TestWaveHelper.Test();
            //TestSoundPlayer.Test();
            //TestZPool.Test();
            //TestSnowflake.Test();
            //TestSecurity.Test();
            //TestGISTrailGenerator.Test();
            //TestValueRangeManager.Test();
            TestSequenceDB.Test();

            //BlockingCollection<int> block = new BlockingCollection<int>();
            //block.Take();
            //Test();

            Console.WriteLine("========================================================");
            Console.WriteLine("q exit");


            while (true)
            {
                string line = Console.ReadLine();
                if (string.Equals(line, "q", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }
            }
            ////TestTelnetServer.Release();
            //TestAsynQueue.Stop();
        }

        unsafe private static void Test()
        {

            using var pointer = new UnmanagedMemoryPointer<byte>(NetHelper.UDP_PACKAGE_MAX);
            Span<byte> span = pointer.GetSpan();
            Socket socket = new Socket(null);
            int len = socket.Receive(span);

            EndPoint endPoint = null;
            int leng2 = socket.ReceiveFrom(span, ref endPoint);


            Span<int> span2 = new Span<int>(pointer.DataPtr, 10);


            CancellationTokenSource cts = new CancellationTokenSource();
            var ret1 = cts.Token.IsCancellationRequested;
            cts.Cancel();
            var ret2 = cts.Token.IsCancellationRequested;

            cts.TryReset();

            bool reset1 = cts.TryReset();
            var ret3 = cts.Token.IsCancellationRequested;
            cts.Cancel();
            var ret4 = cts.Token.IsCancellationRequested;

            var reset2 = cts.TryReset();
            var ret5 = cts.Token.IsCancellationRequested;
            cts.Cancel();
            var ret6 = cts.Token.IsCancellationRequested;

            //byte a = 150;
            //float mul = 2.0f;
            //var ret = a * mul;
            //byte b = (byte)ret;

            //System.ComponentModel.BaseNumberConverter

            //System.ComponentModel.ArrayConverter
            //System.ComponentModel.CollectionConverter

            //System.ComponentModel.ComponentConverter
            //System.ComponentModel.CultureInfoConverter

            //System.ComponentModel.ExpandableObjectConverter
            //System.ComponentModel.GuidConverter
            //System.ComponentModel.NullableConverter


            //System.ComponentModel.DateTimeConverter
            //System.ComponentModel.DateTimeOffsetConverter
            //System.ComponentModel.TimeSpanConverter

            //System.ComponentModel.TypeConverter
            //System.ComponentModel.TypeListConverter

            //System.ComponentModel.BooleanConverter
            //System.ComponentModel.EnumConverter
            //System.ComponentModel.CharConverter
            //System.ComponentModel.StringConverter

            //System.ComponentModel.SingleConverter
            //System.ComponentModel.DoubleConverter
            //System.ComponentModel.DecimalConverter

            //System.ComponentModel.ByteConverter
            //System.ComponentModel.Int16Converter
            //System.ComponentModel.Int32Converter
            //System.ComponentModel.Int64Converter

            //System.ComponentModel.SByteConverter
            //System.ComponentModel.UInt16Converter
            //System.ComponentModel.UInt32Converter
            //System.ComponentModel.UInt64Converter

            //System.ComponentModel.Int128Converter
            //System.ComponentModel.UInt128Converter

            //..net新增加
            //System.ComponentModel.DateOnlyConverter
            //System.ComponentModel.TimeOnlyConverter
            //System.ComponentModel.VersionConverter




            //DeviceTypes value1 = DeviceTypes.CCC;
            //var xx = sizeof(DeviceTypes);
            //var xx2 = Marshal.SizeOf(value1);
            //var convert = new System.ComponentModel.EnumConverter(typeof(DeviceTypes));
            //var str11 = ((int)value1).ToString();


            ////var str11 = (string)convert.ConvertTo(value1, typeof(int));
            //string str = (string)convert.ConvertTo(value1, typeof(string));
            //var value2 = (DeviceTypes)convert.ConvertFrom(str11);




            //var proinfo = typeof(Program).GetProperty("DeviceType");
            //var convert = new UtilZ.Dotnet.Ex.Config.ConfigEnumValueConverter();
            //string str = (string)convert.ConvertTo(proinfo, value1);
            //var value2 = (DeviceTypes)convert.ConvertFrom(proinfo, str);
        }

        public DeviceTypes DeviceType { get; set; }

        public enum DeviceTypes
        {
            AAA = 1,

            BBB = 2,

            CCC = 3,

            DDD = 4
        }

        private static void TestCode()
        {
            //string md5 = HashEx.GetHash("qweQWE123", MD5HashType.MD5CryptoServiceProvider);

            //var names = Directory.GetFiles(@"D:\Projects\UtilZ.DotnetEx\SharedProject\UtilZ.Dotnet.ExAOT\Communication\Net\Telnet\KeyCommands");
            //StringBuilder sb = new StringBuilder();
            //foreach (var name in names)
            //{
            //    sb.AppendLine($" new {Path.GetFileNameWithoutExtension(name)}(),");
            //}
            //string str = sb.ToString();

            //var dic = new Dictionary<string, string>()
            //{
            //    {"name","yf" },
            //    { "age","23"}
            //};
            //var papayloadJson = JsonSerializer.SerializeObject(dic);
            //var dic2 = JsonSerializer.DeserializeObject<Dictionary<string, string>>(papayloadJson);



        }



        private static void DemoeCode()
        {
            //压缩后的值为二进制的10110011，表示数组为[1,0,1,1,0,0,1,1]
            var arr = new Span<byte>(new byte[8]);
            ConvertEx.ByteToBits(0b10110011, arr);
            //byte[] arr = ConvertEx.ByteToBits(0b10110011);

            int count = 1;
            var v1 = Interlocked.Increment(ref count);
            var v3 = Interlocked.Decrement(ref count);

            count = 1;
            int old1 = Interlocked.CompareExchange(ref count, 3, 2);//old1=1

            count = 2;
            int old2 = Interlocked.CompareExchange(ref count, 3, 2);//old2=2
        }

        private static void GenerateErrorCode()
        {
            string fff = @"D:\Projects\BasicLib\ZD784.Base\DWSB\ZD784.DWSB.DDServiceApp\bin\Debug\net8.0-windows\dwdata\1753798306362.dw";
            fff = @"D:\Projects\BasicLib\ZD784.Base\DWSB\ZD784.DWSB.DDServiceApp\bin\Debug\net8.0-windows\dwdata\qwe.dw";
            try
            {
                FileEx.TryDeleFile(fff);

                using var stream1 = new FileStream(fff, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
                using var stream2 = new FileStream(fff, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            }
            catch (Exception ex)
            {
                ConcurrentBag<object> pool = new ConcurrentBag<object>();

                ConcurrentQueue<object> items = new ConcurrentQueue<object>();

            }

            string filePath = @"D:\Projects\DW\dic\B4";
            string dataType = "string";

            string[] lines = System.IO.File.ReadAllLines(filePath);
            var sb = new System.Text.StringBuilder();
            int count = 0;

            for (int i = 0; i < lines.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(lines[i]))
                {
                    continue;
                }

                string line = lines[i].Trim();
                if (line.Trim().StartsWith('*'))
                {
                    continue;
                }

                string[] strs = line.Split('|', StringSplitOptions.RemoveEmptyEntries);
                if (strs.Length != 4)
                {

                }

                if (sb.Length > 0)
                {
                    if (count >= 5)
                    {
                        sb.AppendLine();
                        sb.AppendLine();
                        sb.AppendLine();
                        count = 0;
                    }
                    else
                    {
                        sb.AppendLine();
                    }
                }

                sb.AppendLine(@"        /// <summary>");

                //sb.AppendLine(@"        /// 雷达辐射源扩展项");
                sb.Append(@"        /// ");
                sb.Append(strs[1].Trim());
                sb.Append(',');
                sb.AppendLine(strs[3].Trim());

                sb.AppendLine(@"        /// </summary>");

                //sb.AppendLine(@"        [DisplayNameEx(""雷达辐射源扩展项"")]");
                sb.Append(@"        [DisplayNameEx(""");
                sb.Append(strs[1].Trim());
                sb.AppendLine(@""")]");

                //sb.AppendLine(@"        public const byte 雷达辐射源扩展项 = 1;");
                sb.Append(@"        public const ");
                sb.Append(dataType);
                sb.Append(' ');
                sb.Append(strs[1].Replace('(', '_').Replace(')', '_').Replace('（', '_').Replace('）', '_').Replace('-', '_').Replace(" ", string.Empty).Trim());
                sb.Append(@" = ");

                if (string.Equals(dataType, "string"))
                {
                    sb.Append(@"""");
                    sb.Append(strs[2].Trim());
                    sb.AppendLine(@""";");
                }
                else
                {
                    sb.Append(strs[2].Trim());
                    sb.AppendLine(";");
                }
            }

            //            *联合国UN
            //1 | 外空委COPUOS | B0100112 | 联合国和平利用外层空间委员会UN Committee on the Peaceful Uses of Outer Space

            string code = sb.ToString();
        }

        /// <summary>
        /// 雷达辐射源扩展项
        /// </summary>
        [DisplayNameEx("雷达辐射源扩展项")]
        public const byte 雷达辐射源扩展项 = 1;



        private static void TestLog()
        {
            Loger.Trace("Trace");
            Loger.Debug("Debug");
            Loger.Info("Info");
            Loger.Warn("Warn");
            Loger.Error("Error");
            Loger.Fatal("Fatal");
        }

        private static void InitLog()
        {
            ZLoger.OutputOption = ZLogerOutputOptions.Loger;
            var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
            if (redirectAppenderToUI != null)
            {
                redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
            }
        }

        private static void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            ConsoleColor fontColor;
            string str;
            try
            {
                var item = e.Item;
                str = string.Format("{0} {1}", e.Item.Time.ToString(LogConstant.DateTimeFormat), e.Item.Content);

                switch (item.Level)
                {
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Trace:
                        fontColor = ConsoleColor.Gray;
                        break;
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Debug:
                        fontColor = ConsoleColor.Gray;
                        break;
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Info:
                        fontColor = ConsoleColor.White;
                        break;
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Warn:
                        fontColor = ConsoleColor.Yellow;
                        break;
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Error:
                        fontColor = ConsoleColor.Red;
                        break;
                    case UtilZ.Dotnet.Ex.Log.LogLevel.Fatal:
                        fontColor = ConsoleColor.Red;
                        break;
                    default:
                        return;
                }
            }
            catch (Exception ex)
            {
                fontColor = ConsoleColor.Red;
                str = ex.Message;
            }

            var oldForegroundColor = Console.ForegroundColor;
            Console.ForegroundColor = fontColor;
            Console.WriteLine(str);
            Console.ForegroundColor = oldForegroundColor;
        }
    }
}

